﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.IO;
using System.Threading;
using System.Net.Http;
using System.Configuration;
using Newtonsoft.Json;
using System.Threading.Tasks;
using System.Drawing.Imaging;
using System.Net.Http.Headers;
using Newtonsoft.Json.Linq;
using System.Text.RegularExpressions;
using PdfSharp.Drawing;
using PdfSharp.Pdf;


using iTextSharp.text;
using iTextSharp.text.pdf;


namespace OCX2_SAMPLE1_2
{
    public partial class Form1 : Form
    {
        String PATHS = valueItem("PATHS");

        public Form1()
        {

            InitializeComponent();




            MessageBox.Show("token 为 "+Login.globalToken);

            CefSharp.CefSharpSettings.LegacyJavascriptBindingEnabled = true;


            progressBar1.Value = 0;

            // need set LicenseKey before calling Execute method
            axEScanControl21.LicenseKey = "EPSON";
            axEScanControl21.EParamDeviceInfo.DeviceName = "DS-970";

            // axEScanControl21.EParamScan.DocSource = (int)comboBox2.SelectedValue;
            axEScanControl21.EParamScan.DocSource = 2;

            //axEScanControl21.EParamScan.ImageType = (int)comboBox3.SelectedValue;
            axEScanControl21.EParamScan.ImageType = 0;
            //axEScanControl21.EParamScan.Resolution = (ushort)(int)comboBox4.SelectedValue;
            axEScanControl21.EParamScan.Resolution = 200;
            //axEScanControl21.EParamScan.DocSize = (int)comboBox5.SelectedValue;
            axEScanControl21.EParamScan.DocSize = 2;
            axEScanControl21.EParamScan.DocRotate = -1;
            axEScanControl21.EParamScan.SkewCorrect = 2;  // 矫正偏差

            //axEScanControl21.EParamSave.FileFormat = (int)comboBox6.SelectedValue


            axEScanControl21.EParamSave.FileFormat = 0;


            axEScanControl21.EParamSave.FilePath = PATHS;


            axEScanControl21.EParamOCR.OcrLanguage = 18; // OL_EN
            
            uint ret;
            ret = axEScanControl21.OpenScanner();
      

            ret = axEScanControl21.Execute(1);    // ET_SCAN_AND_SAVE

            progressBar1.Value = 0;


            // DeviceName
            //DeviceName.Text = "DS-970";

            // eDocSource
            //ArrayList dict_eDocSource = new ArrayList();
            //dict_eDocSource.Add(new DictionaryEntry(-1, "Auto"));
            //dict_eDocSource.Add(new DictionaryEntry(0, "Flatbed"));
            //dict_eDocSource.Add(new DictionaryEntry(1, "Feeder - Simplex"));
            //dict_eDocSource.Add(new DictionaryEntry(2, "Feeder - Duplex"));
            //comboBox2.DataSource = dict_eDocSource;
            //comboBox2.ValueMember = "Key";
            //comboBox2.DisplayMember = "Value";
            //comboBox2.SelectedValue = 1;

            // eImageType
            //ArrayList dict_eImageType = new ArrayList();
            //dict_eImageType.Add(new DictionaryEntry(-1, "Auto"));
            //dict_eImageType.Add(new DictionaryEntry(0, "Color"));
            //dict_eImageType.Add(new DictionaryEntry(1, "Gray"));
            //dict_eImageType.Add(new DictionaryEntry(2, "Monochrome"));
            //comboBox3.DataSource = dict_eImageType;
            //comboBox3.ValueMember = "Key";
            //comboBox3.DisplayMember = "Value";
            //comboBox3.SelectedValue = 0;

            // Resolution
            //ArrayList dict_resolution = new ArrayList();
            //dict_resolution.Add(new DictionaryEntry(200, "200dpi"));
            //dict_resolution.Add(new DictionaryEntry(300, "300dpi"));
            //dict_resolution.Add(new DictionaryEntry(600, "600dpi"));
            //comboBox4.DataSource = dict_resolution;
            //comboBox4.ValueMember = "Key";
            //comboBox4.DisplayMember = "Value";
            //comboBox4.SelectedValue = 200;

            // eDocSize
            //ArrayList dict_eDocSize = new ArrayList();
            //dict_eDocSize.Add(new DictionaryEntry(-1, "Auto"));
            //dict_eDocSize.Add(new DictionaryEntry(2, "A4"));
            //dict_eDocSize.Add(new DictionaryEntry(3, "A5"));
            //comboBox5.DataSource = dict_eDocSize;
            //comboBox5.ValueMember = "Key";
            //comboBox5.DisplayMember = "Value";
            //comboBox5.SelectedValue = -1;

            // eFileFormat
            //ArrayList dict_eFileFormat = new ArrayList();
            //dict_eFileFormat.Add(new DictionaryEntry(1, "Jpeg"));
            //dict_eFileFormat.Add(new DictionaryEntry(2, "Tiff"));
            //dict_eFileFormat.Add(new DictionaryEntry(4, "PDF"));
            //comboBox6.DataSource = dict_eFileFormat;
            //comboBox6.ValueMember = "Key";
            //comboBox6.DisplayMember = "Value";
            //comboBox6.SelectedValue = 1;

            progressBar1.Minimum = 0;
            progressBar1.Maximum = 100;
            progressBar1.Value = 0;
        }

        //private void button1_Click(object sender, EventArgs e)
        //{
        //    button1.Enabled = false;

        //    uint ret;
        //    //ret = axEScanControl21.OpenScanner();

        //    ret = axEScanControl21.Execute(0);    // ET_SCAN_AND_SAVE

        //}
        private void button2_Click()
        {
            progressBar1.Value = 0;

            try
            {
                uint ret;

                ret = axEScanControl21.CloseScanner();
                Thread.Sleep(1000);

                
                ret = axEScanControl21.OpenScanner();
                ret = axEScanControl21.Execute(1);    // ET_SCAN_AND_SAVE
            }
            catch (Exception ex)
            {
                // Handle the exception here, you can log it or show an error message
                WriteLog(ex,"", "连接报错");
                MessageBox.Show($"An error occurred: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }


        private void axEScanControl21_OnCompleted(object sender, AxESCANOCX2Lib._IEScanControl2Events_OnCompletedEvent e)
        {
            string messageText;
            messageText = "OnCompleted type = ";
            switch (e.execType)
            {
                case 0:
                    messageText = "ET_SCAN_AND_SAVE";
                    // initImgList();
                    break;
                case 1://不存储图像到本地磁盘,并返回base64
                    messageText = "ET_SCAN_AND_STORE";
                    //richTextBox1.Text = GetBase64String();

                    try
                    {
                        initImgListAsync();

                    }
                    catch (Exception ex)
                    {

                        WriteLog(ex,"", "操作流报错"); ;
                        // Handle the exception here, you can log it or show an error message
                        MessageBox.Show($"An error occurred: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }

                    //imageList1.Images.Add(ConvertBase64ToImage(richTextBox1.Text));


                    break;
                case 2: //存储图像到本地磁盘,并返回base64
                    messageText = "ET_SAVE_STORED_IMAGE";
                    //richTextBox1.Text = GetBase64String();
                    //initImgList();
                    break;
                case 3:
                    messageText = "ET_GET_STORED_IMAGE";

                    break;
                case 4:
                    messageText = "ET_GET_OBR_DATA";
                    break;
                case 5:
                    messageText = "ET_GET_OCR_DATA";
                    //initImgList();
                    break;
            }

            messageText += ", error = ";
            Console.WriteLine(e.errorCode);

            switch (e.errorCode)
            {
                case 0:
                    messageText += "成功";
                    break;
                case 1:
                    messageText += "操作被取消";
                    break;
                case 1073774594:
                    messageText += "请放纸";
                    break;
                case 1073741856:
                    messageText += "卡纸";



                    break;
                case 1073742098:
                    messageText += "检测到双进纸";
                    break;
                case 1074729938:
                    messageText += "缺纸";




                    break;
                case 1074729939:
                    messageText += "ADF Conver 打开";
                    break;
                case -2147483647:
                    messageText += "ESL_ERR_GENERAL";
                    break;
                case -2147483646:
                    messageText += "ESL_ERR_NOT_INITIALIZED";
                    //MessageBox.Show("没有检测到打印机", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    DialogResult result = MessageBox.Show(new Form2(3000), "没有检测到打印机!检查连接", "警告", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
                    if (result == DialogResult.Cancel)
                    {
                        Application.Exit();
                    }
                    Thread.Sleep(2000);
                    break;
                case -2147483645:
                    messageText += "ESL_ERR_FILE_MISSING";
                    break;
                case -2147483644:
                    messageText += "ESL_ERR_INVALID_PARAM";
                    break;
                case -2147483643:
                    messageText += "ESL_ERR_LOW_MEMORY";
                    break;
                case -2147483642:
                    messageText += "ESL_ERR_LOW_DISKSPACE";
                    break;
                case -2147483641:
                    messageText += "ESL_ERR_WRITE_FAIL";
                    break;
                case -2147483640:
                    messageText += "ESL_ERR_READ_FAIL";
                    break;
                case -2147483639:
                    messageText += "ESL_ERR_INVALID_OPERATION";
                    break;

      
                default:
                    messageText += "未知错误";
                    break;
            }


  

            //}
            label1.Text = messageText;


            button2_Click();
        }

        private void axEScanControl21_OnScanStatus(object sender, AxESCANOCX2Lib._IEScanControl2Events_OnScanStatusEvent e)
        {

            progressBar1.Value = e.progress;

            //Console.WriteLine(progressBar1.Value);

        }

        public System.Drawing.Image ConvertBase64ToImage(string base64String)
        {
            byte[] imageBytes = Convert.FromBase64String(base64String);
            using (MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length))
            {
                ms.Write(imageBytes, 0, imageBytes.Length);

                return System.Drawing.Image.FromStream(ms, true);
            }
        }


        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {

            uint ret;
            ret = axEScanControl21.CloseScanner();
        }


   



        //static List<string> GetImagePaths()
        //{
        //    // 这里可以根据实际情况获取图像文件路径列表
        //    // 例如从文件夹中获取或通过其他方式获得
        //    // 这里简单地返回一个示例列表
        //    return new List<string> { "C:/Users/hwb/Desktop/test_image/1.jpg", "C:/Users/hwb/Desktop/test_image/2.jpg" };
        //}

          async Task UploadImages(String apiUrl,List<byte[]> imageBytesList)
        {
          
                using (HttpClient client = new HttpClient())
                using (MultipartFormDataContent form = new MultipartFormDataContent())
                {
                    for (int i = 0; i < imageBytesList.Count; i++)
                    {
                        // 添加文件到表单
                        form.Add(new ByteArrayContent(imageBytesList[i]), "files", $"image{i + 1}.jpg");
                    }

                  

                    // 发送包含文件的请求
                    HttpResponseMessage response = await client.PostAsync(apiUrl, form);

                    // 处理响应
                    if (response.IsSuccessStatusCode)
                    {
                    // 读取响应内容
                    string responseContent = await response.Content.ReadAsStringAsync();

                    // 反序列化
                    YourEntity entities = JsonConvert.DeserializeObject<YourEntity>(responseContent);
                   


                    // 从 entities 获取斜率列表
                    List<double> p1Slope = entities.P1_2;
                    List<double> p2Slope = entities.P2_1;
                    List<double> p3Slope = entities.P3_1;
                    List<double> p4Slope = entities.P3_2;

                    // Check if p1Slope list is not empty and has a count of 4
                    if (p1Slope != null && p1Slope.Count == 4)
                    {
                        if (Math.Abs(p1Slope[0] - 0) > 2)
                        {
                            MessageBox.Show("合格证内容可能是歪的！");
                        }
                        else if (Math.Abs(p1Slope[1] - 90) > 2)
                        {
                            MessageBox.Show("合格证内容可能是歪的！");
                        }
                    }
                    else
                    {
                        MessageBox.Show("请检查纸张数量", "Alert", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }

                    // Check if p2Slope list is not empty and has a count of 4
                    if (p2Slope != null && p2Slope.Count == 4)
                    {
                        if (Math.Abs(p2Slope[0] - 0) > 2)
                        {
                            MessageBox.Show("环保内容可能是歪的");
                        }
                        else if (Math.Abs(p2Slope[1] - 90) > 2)
                        {
                            MessageBox.Show("环保内容可能是歪的");
                        }
                    }
                    else
                    {
                        MessageBox.Show("请检查纸张数量.", "Alert", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }

                    // Check if p3Slope list is not empty and has a count of 4
                    if (p3Slope != null && p3Slope.Count == 4)
                    {
                        if (Math.Abs(p3Slope[0] - 0) > 2)
                        {
                            MessageBox.Show("一致性证书可能是歪的");
                        }
                        else if (Math.Abs(p3Slope[1] - 90) > 2)
                        {
                            MessageBox.Show("一致性证书可能是歪的");
                        }
                    }
                    else
                    {
                        MessageBox.Show("请检查纸张数量.", "Alert", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }

                    // Check if p4Slope list is not empty and has a count of 4
                    if (p4Slope != null && p4Slope.Count == 4)
                    {
                        if (Math.Abs(p4Slope[0] - 0) > 2)
                        {
                            MessageBox.Show("一致性证书背面可能是歪的");
                        }
                        else if (Math.Abs(p4Slope[1] - 90) > 2)
                        {
                            MessageBox.Show("一致性证书可能是歪的");
                        }
                    }
                    else
                    {
                        MessageBox.Show("请检查纸张数量", "Alert", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }






                    //if (entities.P1_1_num != null && entities.P1_1_num.ToString().Length >= 17)
                    //{
                    //MessageBox.Show("首页标签没问题");
                    entities.P1_cjh = "LFMCC1BR2P0672669";
                    entities.P1_1_num = "LFMCC1BR2P0672669";
                    entities.P2_ewm = "LFMCC1BR2P0672669";
                    entities.P3_sbdh = "LFMCC1BR2P0672669";

                    if (entities.P1_1_num != null)
                    {
                        if (entities.P1_cjh != null)
                    {
                        if (entities.P2_ewm != null)
                        {
                        if (entities.P3_sbdh != null)
                        {



                            string P1_cjh = entities.P1_cjh;
                            string P1_1_num = entities.P1_1_num;
                            string P2_ewm = entities.P2_ewm;
                            string P3_sbdh = entities.P3_sbdh;
                                    panel1.Visible = true;
                                    textBox2.Text = P1_1_num;
                                    textBox3.Text = RemoveChinese(P1_cjh);
                                    textBox4.Text = P2_ewm;
                                    textBox5.Text = RemoveChinese(P3_sbdh);

                                    if (P1_cjh.Contains(P2_ewm))
                            {
                                Console.WriteLine("P1_cjh 包含 P2_ewm");

                            }
                            else
                            {
                                panel1.Visible = true;
                                textBox2.Text = P1_1_num;
                                textBox3.Text = RemoveChinese(P1_cjh);
                                textBox4.Text = P2_ewm;
                                textBox5.Text = RemoveChinese(P3_sbdh);




                            }

                            if (P1_1_num.Contains(P2_ewm))
                            {
                                Console.WriteLine("P1_1_num 包含 P2_ewm");


                            }
                            else
                            {
                                panel1.Visible = true;
                                textBox2.Text = P1_1_num;
                                textBox3.Text = RemoveChinese(P1_cjh);
                                textBox4.Text = P2_ewm;
                                textBox5.Text = RemoveChinese(P3_sbdh);

                            }

                            if (P3_sbdh.Contains(P2_ewm))
                            {
                                Console.WriteLine("P3_sbdh 包含 P2_ewm");


                            }
                            else
                            {
                                panel1.Visible = true;
                                textBox2.Text = P1_1_num;
                                textBox3.Text = RemoveChinese(P1_cjh);
                                textBox4.Text = P2_ewm;
                                textBox5.Text = RemoveChinese(P3_sbdh);
                            }

                            if (panel1.Visible == false)
                            {
                                // 将imageBytesList 合成pdf


                                if (imageBytesList != null && imageBytesList.Count > 0)
                                {


                                    await UploadPdfContentToApi(imageBytesList, P2_ewm);
                                    Console.WriteLine("PDF created successfully.");



                                }
                                else
                                {
                                    Console.WriteLine("No images to convert.");
                                }




                            }



                            // 从 entities 中获取属性值并去掉中文字符
                            //string P1_cjh = RemoveChinese(entities.P1_cjh);
                            //string P1_1_num = entities.P1_1_num;
                            //string P2_ewm = entities.P2_ewm;
                            //string P3_sbdh = RemoveChinese(entities.P3_sbdh);

                            // 计算字符串相似度
                            //double similarity_P1_cjh_P1_1_num = CalculateSimilarity(P2_ewm, P1_1_num);


                            //double similarity_P1_cjh_P2_ewm = CalculateSimilarity(P2_ewm,P1_cjh);


                            //double similarity_P1_cjh_P3_sbdh = CalculateSimilarity(P2_ewm, P3_sbdh);

                            // ... 继续比较其他字符串的相似性

                            // 输出P1_cjh, P1_1_num





                            // ... 输出其他字符串的相似性






                        }
                        else
                        {

                            MessageBox.Show("一致性没检测出来，请查看排放位置");


                        }



                    }
                    else
                        {
                            MessageBox.Show("环保二维码没识别，请确认");






                        }

                    }
                    else
                    {
                        MessageBox.Show("合格证背面VIN未识别");






                    }




                        //  //  P1_1_num 属性的值大于 17 位
                    }
                    else
                    {
                        MessageBox.Show("首页标签没帖，或者破损");
                        // P1_1_num 属性的值为空或不大于 17 位
                    }










                    // 输出其他属性...





                    // 处理响应内容，这里假设 API 返回的是 JSON 数据
                    Console.WriteLine("图像文件上传成功！");
                    Console.WriteLine("响应内容：" + responseContent);
                }
                    else
                    {


                    MessageBox.Show("识别服务没有连上");
                        Console.WriteLine($"图像文件上传失败，错误码：{response.StatusCode}");
                    }
                }
            }



        static void ConvertImagesToPdf(List<byte[]> imageBytesList, string outputPath)
        {
            using (Document doc = new Document())
            {
                using (FileStream fs = new FileStream(outputPath, FileMode.Create))
                {
                    PdfWriter.GetInstance(doc, fs);
                    doc.Open();
                    foreach (byte[] imageBytes in imageBytesList)
                    {
                        using (MemoryStream ms = new MemoryStream(imageBytes))
                        {
                            System.Drawing.Image image = System.Drawing.Image.FromStream(ms);
                            if (image != null)
                            {
                                doc.NewPage();

                                //// Adding additional space for the image within the page
                                //iTextSharp.text.Rectangle pageSize = new iTextSharp.text.Rectangle(image.Width + 550, image.Height + 550);
                                //doc.SetPageSize(pageSize);
                                iTextSharp.text.Rectangle pageSize = PageSize.A4;

                                iTextSharp.text.Image pdfImage = iTextSharp.text.Image.GetInstance(image, System.Drawing.Imaging.ImageFormat.Png);
                                pdfImage.ScaleToFit(pageSize.Width, pageSize.Height); // Scale the image to fit the entire page
                                pdfImage.SetAbsolutePosition(0, 0); // Set image position at (0, 0)

                                doc.Add(pdfImage);
                            }
                        }
                    }
                    doc.Close();
                }
            }
        }

        static async Task<byte[]> GeneratePdfContent(List<byte[]> imageBytesList)
        {
            using (MemoryStream memoryStream = new MemoryStream())
            {
                using (Document doc = new Document(PageSize.A4))
                {
                    PdfWriter writer = PdfWriter.GetInstance(doc, memoryStream);
                    writer.CloseStream = false; // 防止关闭流

                    doc.Open();

                    foreach (byte[] imageBytes in imageBytesList)
                    {
                        using (MemoryStream ms = new MemoryStream(imageBytes))
                        {
                            System.Drawing.Image image = System.Drawing.Image.FromStream(ms);
                            if (image != null)
                            {
                                iTextSharp.text.Image pdfImage = iTextSharp.text.Image.GetInstance(image, System.Drawing.Imaging.ImageFormat.Png);
                                pdfImage.ScaleToFit(PageSize.A4.Width, PageSize.A4.Height);

                                // 计算图像应该位于页面的右上角
                                float xPosition = PageSize.A4.Width - pdfImage.ScaledWidth;
                                float yPosition = PageSize.A4.Height - pdfImage.ScaledHeight;

                                pdfImage.SetAbsolutePosition(xPosition, yPosition);
                                doc.Add(pdfImage);
                                doc.NewPage();
                            }
                        }
                    }

                    doc.Close(); // 关闭文档
                    writer.Close(); // 关闭 PdfWriter
                }

                memoryStream.Position = 0; // 重置内存流的位置到开头
                byte[] pdfBytes = memoryStream.ToArray(); // 将生成的PDF文件内容转换为字节数组
                return pdfBytes;
            }
        }



        static async Task UploadPdfContentToApi(List<byte[]> imageBytesList,string vinNO)
        {
            byte[] pdfBytes = await GeneratePdfContent(imageBytesList);

            using (MemoryStream memoryStream = new MemoryStream(pdfBytes))
            using (HttpClient client = new HttpClient())
            {
                var content = new MultipartFormDataContent();
                var fileContent = new StreamContent(memoryStream);
                fileContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/pdf");
                string timeStamp = DateTime.Now.ToString("ddmmss"); // 生成时间戳
                string fileNameWithTimeStamp = vinNO + "_" + timeStamp + ".pdf"; // 将时间戳添加到文件名中
                content.Add(fileContent, "file", fileNameWithTimeStamp); // 使用带有时间戳的文件名

                content.Add(new StringContent(vinNO), "vinNo");

                var response = await client.PostAsync(valueItem("MINIO_IP"), content);

                if (response.IsSuccessStatusCode)
                {
                    // 读取响应内容
                    string responseContent = await response.Content.ReadAsStringAsync();
                    Console.WriteLine("File uploaded successfully.");

                    // 解析 JSON 获取 code 值
                    JObject jsonResponse = JObject.Parse(responseContent);
                    int code = jsonResponse["code"].Value<int>();

                    if (code == 250)
                    {
                        // 在这里弹出消息框
                        MessageBox.Show("生产指示没有数据！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }

                    MessageBox.Show("上传成功");
                    Console.WriteLine("File uploaded successfully.");
                }
                else
                {
                    Console.WriteLine("File upload failed. Status code: " + response.StatusCode);
                }
            }
        }












        public static void WriteLog(Exception ex, string LogAddress,string EXC)
        {  

            //如果日志文件为空，则默认在Debug目录下新建 YYYY-mm-dd_Log.log文件
            if (LogAddress == "")
            {
                LogAddress = Environment.CurrentDirectory + '\\' +
                    DateTime.Now.Year + '-' +
                    DateTime.Now.Month + '-' +
                    DateTime.Now.Day + "_Program.log";
            }
            //把异常信息输出到文件
            StreamWriter fs = new StreamWriter(LogAddress, true);
            fs.WriteLine("当前时间：" + DateTime.Now.ToString());
            fs.WriteLine("异常信息：" + ex.Message);
            fs.WriteLine("异常对象：" + ex.Source);
            fs.WriteLine("调用堆栈：\n" + ex.StackTrace.Trim());
            fs.WriteLine("触发方法：" + ex.TargetSite);
            fs.WriteLine("错误：" +EXC);
            fs.WriteLine();
            

            fs.Close();
        }
    










    // 去掉字符串中的中文字符
    static string RemoveChinese(string input)
        {
            if (string.IsNullOrEmpty(input))
            {
                return input; // 输入字符串为空，直接返回
            }

            string pattern = @"[\u4e00-\u9fa5]"; // 中文字符的 Unicode 范围
            string result = Regex.Replace(input, pattern, ""); // 使用正则表达式替换中文字符为空字符串

            return result;
        }

        // 计算字符串相似度的函数（Levenshtein 距离）
        static double CalculateSimilarity(string str1, string str2)
        {
            int maxLen = Math.Max(str1.Length, str2.Length);
            if (maxLen == 0)
                return 1.0; // 如果两个字符串都为空，相似度为1

            int distance = LevenshteinDistance(str1, str2);
            return 1.0 - (double)distance / maxLen;
        }
        // 计算 Levenshtein 距离的方法
        static int LevenshteinDistance(string str1, string str2)
        {
            int len1 = str1.Length;
            int len2 = str2.Length;

            int[,] dp = new int[len1 + 1, len2 + 1];

            for (int i = 0; i <= len1; i++)
                dp[i, 0] = i;

            for (int j = 0; j <= len2; j++)
                dp[0, j] = j;

            for (int i = 1; i <= len1; i++)
            {
                for (int j = 1; j <= len2; j++)
                {
                    int cost = (str2[j - 1] == str1[i - 1]) ? 0 : 1;
                    dp[i, j] = Math.Min(
                        Math.Min(dp[i - 1, j] + 1, dp[i, j - 1] + 1),
                        dp[i - 1, j - 1] + cost);
                }
            }

            return dp[len1, len2];
        }

        static byte[] ImageToByteArray(System.Drawing.Image image)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                image.Save(ms, ImageFormat.Jpeg);
                return ms.ToArray();
            }
        }








        private async Task initImgListAsync()
        {

            if (axEScanControl21.EStoredPages.count > 0)
            {
                ImageList imglist = new ImageList();
                imglist.Images.Clear();
                List<string> lstName = new List<string>();
                imglist.ImageSize = new Size(160, 256);
                imglist.ColorDepth = ColorDepth.Depth32Bit;
                List<byte[]> imageBytesList = new List<byte[]>();

                for (int i = 0; i < axEScanControl21.EStoredPages.count; i++)
                {


                    ESCANOCX2Lib.EPage page;


                    page = (ESCANOCX2Lib.EPage)axEScanControl21.EStoredPages.Item(i);
                    // 将图像从Base64字符串转换为Image

                    System.Drawing.Image image;
                    // 将 Base64 字符串转换为字节数组
                    byte[] imageBytes = Convert.FromBase64String(page.EImage.Image.ToString());
                    imageBytesList.Add(imageBytes);

                    // 创建一个内存流，将图像数据写入其中
                    using (MemoryStream ms = new MemoryStream(imageBytes))
                    {
                        // 创建图像对象
                        image = System.Drawing.Image.FromStream(ms);
                        string fileName = $"{DateTime.Now.ToString("yyyyMMddHHmmss")}{i}.jpg";
                        // 指定本地文件路径，包括文件名和扩展名

                        string filePath = Path.Combine(PATHS, fileName);

                        if (!Directory.Exists(PATHS))
                        {
                            Directory.CreateDirectory(PATHS);
                        }
                        // 保存图像到本地文件，可以指定图像格式
                        image.Save(filePath); // 保存为 PNG 格式


                    }
                    imglist.Images.Add(image);
                    // 记住在不再需要的时候释放图像对象







                    lstName.Add(i.ToString());

                    //Pages++;
                }

    

               // string apiUrl = "http://localhost:8000/process_images/";

                // Create and populate an ImageList
                // ImageList imglist = new ImageList();
                // Add images to imglist based on your logic
                // imglist.Images.Add(...);
               // List<string> imagePaths = GetImagePaths();

                // 将图像文件转换为字节数组列表
             //   List<byte[]> imageBytesList = ConvertImagesToBytes(imagePaths);

                // 上传图像文件到服务器
                await UploadImages(valueItem("CHIMAGE_URL"), imageBytesList);


                

                //}
                if (listView1.LargeImageList != null && listView1.LargeImageList.Images.Count > 0)
                {
                    listView1.LargeImageList.Images.Clear();
                    listView1.Items.Clear();
                }
                listView1.LargeImageList = imglist;

                for (int i = 0; i < imglist.Images.Count; i++)
                {

                    ListViewItem lvi = new ListViewItem();
                    lvi.ImageIndex = i;
                    //lvi.Text = lstName[i].Substring(0, lstName[i].IndexOf("."));
                    lvi.Text = lstName[i].ToString();
                    listView1.Items.Add(lvi);

                }


            }
        }


        //static List<byte[]> ConvertImagesToBytes(List<string> imagePaths)
        //{
        //    List<byte[]> imageBytesList = new List<byte[]>();

        //    foreach (var imagePath in imagePaths)
        //    {
        //        // 读取文件内容
        //        byte[] fileContent = File.ReadAllBytes(imagePath);

        //        // 将字节数组添加到列表
        //        imageBytesList.Add(fileContent);
        //    }

        //    return imageBytesList;
        //}



        public static string valueItem(string keyName)
        {
            //返回配置文件中键为keyName的项的值
            return ConfigurationManager.AppSettings[keyName];
        }
        private async void button1_ClickAsync(object sender, EventArgs e)
        {






            var client = new HttpClient();
            var request = new HttpRequestMessage(HttpMethod.Post,valueItem("IP_COM")+ "/project/certificateScan/appCodeList");
      //      var content = new StringContent("{\r\n    \"vinNo\":\"LFMCC1BRXP0662147\"\r\n}", null, "application/json");
            var content = new StringContent("{\r\n    \"vinNo\":\""+textBox1.Text+"\"\r\n}", null, "application/json");
            request.Content = content;
            var response = await client.SendAsync(request);
            response.EnsureSuccessStatusCode();
     //       Console.WriteLine(await response.Content.ReadAsStringAsync());
        //    String s = await response.Content.ReadAsStringAsync();
            var responseObj = JsonConvert.DeserializeObject<SelectClass>(await response.Content.ReadAsStringAsync());

            // Access the "pdfUrl" field
            if (responseObj.data != null)
            {
                string pdfUrl = responseObj.data.pdfUrl;
                chromiumWebBrowser1.Load(pdfUrl);
                Console.WriteLine(pdfUrl);
            }
            else
            {

                MessageBox.Show("没有找到pdf");
            
            }



  









        }

        private void button2_Click(object sender, EventArgs e)
        {
            panel1.Visible = false;
        }

        private async void button3_Click(object sender, EventArgs e)
        {
            bool confirmed = ConfirmVINModification();

            if (confirmed)
            {
                List<byte[]> imageBytesList = new List<byte[]>();

                foreach (ListViewItem item in listView1.Items)
                {
                    int imageIndex = item.ImageIndex;
                    if (imageIndex >= 0 && imageIndex < listView1.LargeImageList.Images.Count)
                    {
                        System.Drawing.Image image = listView1.LargeImageList.Images[imageIndex];
                        byte[] imageBytes = ImageToByteArray(image); // 将图像转换为字节数组
                        imageBytesList.Add(imageBytes); // 将图像字节数组添加到列表中
                    }
                    else
                    {
                        // 处理找不到图像的情况
                    }
                }

                await UploadPdfContentToApi(imageBytesList, textBox4.Text); // 上传图像字节数组列表和 VIN 号

                panel1.Visible = false;
                


            }
            else
            {
                // 用户选择了取消操作
            }
        }


        private bool ConfirmVINModification()
        {
            DialogResult result = MessageBox.Show("请确定修改 VIN", "确认上传", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);

            if (result == DialogResult.OK)
            {
                return true; // 用户选择了确定操作
            }
            else
            {
                return false; // 用户选择了取消操作
            }
        }

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (char.IsLetterOrDigit(e.KeyChar) || e.KeyChar == 8)
                e.Handled = false;
            else
                e.Handled = true;
        }

        private void textBox5_TextChanged(object sender, EventArgs e)
        {

        }

        private void textBox4_TextChanged(object sender, EventArgs e)
        {

        }
    }
    }



    //public class YourEntity
    //{
    //    public string P1_ewm { get; set; }
    //    public string P1_2 { get; set; }
    //    public string P1_fdjh { get; set; }
    //    public string P1_clxh { get; set; }
    //    public string P1_cjh { get; set; }
    //    public string P1_fdjxh { get; set; }
    //    public string P1_1 { get; set; }
    //    public string P1_1_num { get; set; }

    //    public string P2_1 { get; set; }
    //    public string P2_2 { get; set; }
    //    public string P2_ewm { get; set; }
    //    public string P2_fdjbh { get; set; }
    //    public string P2_clxh { get; set; }
    //    public string P2_fdjxh_xiao { get; set; }
    //    public string P2_fdjxh { get; set; }

    //    public string P3_1 { get; set; }
    //    public string P3_sbdh { get; set; }
    //    public string P3_fdjbh { get; set; }
    //    public string P3_ewm { get; set; }
    //    public string P3_clxh { get; set; }
    //    public string P3_fdjxh_xiao { get; set; }
    //    public string P3_fdjxh { get; set; }
    //    public string P3_2 { get; set; }
    //}


public class YourEntity
{
    public string P1_1 { get; set; }
    public string P1_1_num { get; set; }
    public string P1_clxh { get; set; }
    public string P1_cjh { get; set; }
    public string P1_fdjxh { get; set; }
    public string P1_fdjh { get; set; }
    public string P1_ewm { get; set; }
    public List<double> P1_2 { get; set; }

    public List<double> P2_1 { get; set; }
    public List<double> P2_2 { get; set; }
    public string P2_ewm { get; set; }
    public string P2_fdjbh { get; set; }
    public string P2_clxh { get; set; }
    public string P2_fdjxh_xiao { get; set; }
    public string P2_fdjxh { get; set; }

    public List<double> P3_1 { get; set; }
    public string P3_sbdh { get; set; }
    public string P3_fdjbh { get; set; }
    public string P3_ewm { get; set; }
    public string P3_clxh { get; set; }
    public string P3_fdjxh_xiao { get; set; }
    public string P3_fdjxh { get; set; }
    public List<double> P3_2 { get; set; }
}


